<?php

namespace App\Modules\System\Commands;

use App\Modules\Order\Models\Order;
use Illuminate\Console\Command;

class Rank extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'rank:refresh';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '更新排行榜';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        Order::query()
            ->where('created_at', '>', now()->subDays(15)->toDateTimeString())
            ->whereNotNull('referrer_id')
            ->where('referrer_level', '>', 0)
            ->where('status', Order::STATUS_PAID)
            ->selectRaw('sum(original_price) as money, count(1) as count, date_format(created_at, "%Y-%m-%d") as date,referrer_level, referrer_id, shop_id')
            ->groupBy(['referrer_level', 'referrer_id', 'shop_id', 'date'])
            ->orderBy('referrer_id')
            ->each(function ($item) {
                \App\Modules\System\Models\Rank::query()
                    ->updateOrCreate([
                        'user_id' => $item->referrer_id,
                        'shop_id' => $item->shop_id,
                        'level' => $item->referrer_level,
                        'date' => $item->date,
                    ], [
                        'money' => $item->money,
                        'number' => $item->count,
                    ]);
            });
    }
}
